<template>
  <VPage class="task-develop">
    <VTable
      ref="tableRef"
      v-bind="tableOptins"
      class="is--card is--line"
      @keyup="handleKeyUp"
    >
      <template #form="{ form }">
        <select-category
          ref="selectCategory"
          style="width: 200px"
          v-model="form.product_category_array"
          placeholder="产品分类"
          :defaultProps="defaultProps"
          filterable
          :showAllLevels="false"
          @change="changeCategory"
        ></select-category>
        <el-input
          v-model.trim="form.product_title"
          placeholder="产品名称"
          clearable
          class="!w-[160px]"
        />
        <el-select
          class="!w-[160px]"
          v-model="form.attribute_type"
          collapse-tags
          placeholder="产品类型"
          clearable
        >
          <el-option
            v-for="item in options['product.Product']?.[0].attributeTypeText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <VGroup>
          <el-select class="selectClass !w-[100px]" v-model="form.taskRange.type">
            <el-option
              v-for="item in taskOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <multi-input
            clearable
            v-model="form.taskRange.value"
            style="width: 200px"
            placeholder="批量搜索,一行一个"
          ></multi-input>
        </VGroup>

        <VGroup class="no-border">
          <div class="v-group-item form-item-bgColor">产品毛利率</div>
          <el-input-number
            class="w-[100px]"
            v-model="form.estimated_product_gross_margin.start"
            :controls="false"
            placeholder="输入"
          />
          <div class="v-group-item no-border-item"><svg-icon icon-class="qujian" /></div>
          <el-input-number
            class="w-[100px]"
            v-model="form.estimated_product_gross_margin.end"
            :controls="false"
            placeholder="输入"
          />
        </VGroup>
        <VGroup class="no-border">
          <div class="v-group-item form-item-bgColor">销售毛利率</div>
          <el-input-number
            class="w-[100px]"
            v-model="form.estimated_sale_gross_margin.start"
            :controls="false"
            placeholder="输入"
          />
          <div class="v-group-item no-border-item"><svg-icon icon-class="qujian" /></div>
          <el-input-number
            class="w-[100px]"
            v-model="form.estimated_sale_gross_margin.end"
            :controls="false"
            placeholder="输入"
          />
        </VGroup>
        <el-input
          class="!w-[220px]"
          v-model="form.competitor_link"
          placeholder="竞品链接"
        ></el-input>
        <VGroup>
          <select-platform-site
            v-model:platform="form.platform_id"
            v-model:site="form.site"
            :sitemultiple="true"
            platformPlaceholder="推荐平台"
            sitePlaceholder="站点"
          ></select-platform-site>
        </VGroup>
        <VGroup>
          <el-select class="selectClass !w-[100px]" v-model="form.personnelRange.type">
            <el-option
              v-for="item in personnelOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <select-personnel
            class="w-50"
            v-model="form.personnelRange.value"
            :multiple="true"
            placeholder="请选择"
          ></select-personnel>
        </VGroup>
        <VGroup>
          <el-select
            class="selectClass !w-[130px]"
            v-model="form.operationPersonnelRange.type"
          >
            <el-option
              v-for="item in operationPersonnelOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <select-personnel
            class="!w-[180px]"
            v-model="form.operationPersonnelRange.value"
            :multiple="true"
            placeholder="请选择"
          ></select-personnel>
        </VGroup>
        <el-select
          class="!w-[220px]"
          v-model="form.check_status"
          placeholder="运营审核结果"
          multiple
          collapse-tags
          clearable
        >
          <el-option
            v-for="item in options['product.ProductFee']?.[0].checkStatusText"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <VGroup>
          <el-select class="selectClass w-[130px]" v-model="form.dateRange.type">
            <el-option
              v-for="item in dateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="form.dateRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime()"
          />
        </VGroup>

        <teleport v-if="tabsLoad" to="#develop-tab">
          <el-tabs
            class="w-full"
            v-if="tabList.length"
            v-model="form.status"
            @tab-click="handleClick"
          >
            <el-tab-pane
              :label="item.status_text"
              :name="item.status"
              v-for="(item, index) in tabList"
              :key="index"
            >
              <template #label>
                {{ item.status_text }}(<span
                  :class="
                    form.status == item.status ? 'base-text-color' : 'text-[#999999]'
                  "
                  >{{ item.count }}</span
                >)
              </template>
            </el-tab-pane>
          </el-tabs>
        </teleport>
      </template>

      <template #toolbar_btns>
        <div id="develop-tab" class="w-full" v-dom-load="() => (tabsLoad = true)"></div>
        <VButton auth="/goods/task/develop/add" type="primary" @click="add"
          ><svg-icon icon-class="add_new" />新增</VButton
        >
        <VButton auth="/goods/task/develop/copy" @click="copy">
          <svg-icon icon-class="copy" />复制</VButton
        >
        <VButton
          auth="/goods/task/develop/submitAudit"
          :loading="loadings.submitAudit"
          @click="submitAudit('submitAudit')"
          >提交开发审核</VButton
        >
        <VButton auth="/goods/task/develop/audit" @click="handleAudit()"
          >开发审核</VButton
        >
        <VButton
          auth="/goods/task/develop/operation-audit"
          :loading="loadings.submitAudit"
          @click="submitOperationAudit()"
          >提交运营审核</VButton
        >
        <VButton
          auth="/goods/task/develop/operationaudit"
          :loading="loadings.submitAudit"
          @click="handleBatchOperationAudit()"
          >运营审核</VButton
        >
        <VButton auth="/goods/task/develop/withdraw" @click="handleWithdraw()"
          >撤回</VButton
        >
        <div class="ml-auto">
          <VButton auth="/goods/task/develop/import" @click="handleImport()">
            <i class="dk-iconfont icon-Download" />导入新增</VButton
          >
          <VButton
            class="!ml-[12px]"
            auth="/goods/task/develop/export"
            @click="handleExport('goods_product_list')"
          >
            <i class="dk-iconfont icon-Upload" />导出</VButton
          >
        </div>
      </template>
      <template #headerExpand>
        <div
          class="cursor-pointer text-xs text-[#3487ff] -ml-[5px]"
          @click="handleExpand()"
        >
          展开/收拢
        </div>
      </template>
      <template #expand_content="{ row }">
        <div class="">
          <table class="w-full table-inside" border="1">
            <tr v-for="(item, index) in row.product_fee_list" :Key="item.id">
              <td width="120">
                <div class="text-center">
                  {{ item.platform_id_text }} - {{ item.site_text }}
                </div>
                <div class="text-center" v-if="item.product_level_text">
                  {{ item.product_level_text }}级
                </div>
              </td>
              <td width="60">
                <div :style="`color:${getTextColor(item.check_status)}`">
                  {{ item.check_status_text }}
                </div>
              </td>
              <td width="180">
                <div><span>运营:</span>{{ item.operation_user_id_text }}</div>
                <div>
                  <span>指定运营:</span>{{ item.specified_operation_user_id_text }}
                </div>
              </td>
              <td width="160">
                <div>
                  <span>建议售价:</span
                  ><span class="!text-[#ff0000]">{{ item.selling_price }}</span>
                  {{ item.currency_name }}
                </div>
                <div>
                  <span>兑人民币:</span
                  ><span class="!text-[#ff0000]">{{
                    calculateAgainstRMB(item.selling_price, item.exchange_rate)
                  }}</span
                  >CNY
                </div>
              </td>
              <td width="160">
                <div><span>汇率:</span>{{ item.exchange_rate }}</div>
                <div>
                  <span>采购成本:</span
                  >{{ item.purchase_cost ? item.purchase_cost + " CNY" : "" }}
                </div>
              </td>
              <td width="140">
                <div>
                  <span>预估产毛率:</span
                  ><span class="!text-[#ff0000]">{{
                    item.estimated_product_gross_margin
                  }}</span
                  >%
                </div>
                <div>
                  <span>预估销毛率:</span
                  ><span class="!text-[#ff0000]">{{
                    item.estimated_sale_gross_margin
                  }}</span
                  >%
                </div>
              </td>
              <td width="140">
                <div class="flex">
                  <span>备货量:</span>
                  <div class="!text-[#ff0000]">{{ item.suggest_prepare_count }}</div>
                </div>
                <div><span>备货金额:</span>{{ calculateStockTotal(item) }}CNY</div>
              </td>
              <td width="200">
                <div class="w-[200px]">
                  <vText
                    title="头程"
                    :value="`【${item.head_freight}CNY】-${
                      item.head_logistic_channel || ''
                    }`"
                  ></vText>
                  <vText
                    title="尾程"
                    :value="`【${item.tail_freight}CNY】-${
                      item.tail_logistic_channel || ''
                    }`"
                  ></vText>
                </div>
              </td>
              <td width="120">
                <div class="w-[120px]">
                  <vText
                    :value="item.product_link"
                    type="button"
                    copy
                    @click="openLink(item.product_link)"
                  ></vText>
                </div>
              </td>
              <td width="140">
                <div><span>重量:</span>{{ item.gross_weight_g }}g</div>
                <div>
                  <span>尺寸:</span>{{ item.packing_specification?.length }}*{{
                    item.packing_specification?.width
                  }}*{{ item.packing_specification?.height }}cm
                </div>
              </td>
              <td width="200">
                <div class="w-[200px]">
                  <vText title="详情备注" :value="item.remark"></vText>
                  <vText title="审核备注" :value="item.check_remark"></vText>
                </div>
              </td>
              <td width="200">
                <div><span>审核时间:</span>{{ item.check_time }}</div>
              </td>
            </tr>
          </table>
        </div>
      </template>
    </VTable>
    <AddModal ref="addref" @query="queryForm"></AddModal>
    <Audit ref="AuditRef" @query="queryForm"></Audit>
    <SubmitAudit ref="SubmitAuditRef" @query="queryForm"></SubmitAudit>
    <el-dialog
      v-model="visible"
      title="备注"
      width="600"
      show-footer
      draggable
      :z-index="2000"
    >
      <p v-html="remark"></p>
      <template #footer>
        <el-button type="primary" @click="visible = false">确定</el-button>
      </template>
    </el-dialog>
  </VPage>
  <VLog ref="productLog" class="dialogPublic" :api="api.log" options="productId"></VLog>
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <OperationAudit ref="operationAuditRef" @refresh="refresh" />
  <importData ref="importExcelRef">
    <template #footer>
      <div class="text-[#999999]">
        <div>1、只支持新增，一次最多200条数据；</div>
        <div>2、若同一个任务需要维护多条推荐平台/站点，则任务ID需保持一致；</div>
        <div>3、请下载最新导入模版进行导入</div>
        <div>
          4、导入的数据较多时，导入处理时间较长，请耐心等待；导入完毕后，异常数据支持下载；
        </div>
      </div>
    </template>
  </importData>
  <BatchOperationAudit ref="BatchOperationAuditRef"></BatchOperationAudit>
  <GenerateSKU ref="GenerateSKURef"></GenerateSKU>
</template>

<script setup lang="jsx" name="TaskDevelop">
import { ElMessage, ElMessageBox } from "element-plus";
import VImage from "@/components/Image/index.vue";
import VLog from "@/components/VLog";
import AddModal from "./components/AddModal.vue";
import Audit from "./components/AuditModal.vue";
import SubmitAudit from "./components/SubmitAudit.vue";
import { getOptions } from "@/api/index.js";
import api from "./api";
import { useRouter } from "vue-router";
import SelectCategory from "@/components/SelectCategory";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import DerivedCenter from "@/components/DerivedCenter";
import importData from "@/components/importData";
import {
  personnelOption,
  dateOptions,
  operationPersonnelOption,
  taskOptions,
} from "./data.js";
import OperationAudit from "./components/OperationAudit/index.vue";
import BatchOperationAudit from "./components/OperationAudit/batch.vue";
import GenerateSKU from "./components/GenerateSKU.vue";
import { calculateAgainstRMB, calculateStockTotal } from "./utils.js";
import { openLink } from "@/utils/index.js";

const router = useRouter();
const tableRef = ref(null);
const addref = ref(null);
const AuditRef = ref(null);
const options = ref([]);
const records = ref([]);
const visible = ref(false);
const remark = ref("");
const loadings = reactive({
  submitAudit: false,
  del: false,
  submitAuditRow: false,
});
const tabsLoad = ref(false);

provide("options", options);
onMounted(() => {
  nextTick(() => {
    fetchOption();
  });
});

const data = reactive({
  tabList: [],
  expandStatus: false,
});
const { tabList, expandStatus } = toRefs(data);

const tableOptins = reactive({
  expandConfig: {
    padding: true,
    mode: "inside",
    defaultExpandAll: false, // 默认不展开任何行
  },
  formConfig: {
    save: "develop", // 必填，唯一
    data: {
      estimated_sale_gross_margin: {
        start: null,
        end: null,
      },
      estimated_product_gross_margin: {
        start: null,
        end: null,
      },
      dateRange: {
        type: "create_time",
        value: "",
        range: true,
      },
      personnelRange: {
        type: "developer_id",
        value: "",
      },
      operationPersonnelRange: {
        type: "operation_id",
        value: "",
      },
      status: "",
      product_category: [],
      product_category_array: [],
      taskRange: {
        type: "product_no",
        value: "",
      },
    },
  },
  rowConfig: {
    height: 80,
  },
  scrollY: {
    enabled: true,
    gt: 10,
  },
  columns: [
    { type: "checkbox", width: 50, fixed: "left" },
    {
      type: "expand",
      width: 70,
      fixed: "left",
      slots: {
        header: "headerExpand",
        default: ({ row }) => {
          return (
            <span class="text-[#3487ff] -ml-2">({row.product_fee_list.length})</span>
          );
        },
        content: "expand_content",
      },
    },
    {
      title: "产品",
      width: 400,
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex justify-start pr-3">
              <div class="relative">
                <VImage
                  src={row.product_main_img_watermark || row.product_main_img}
                  width={60}
                  height={60}
                ></VImage>
              </div>
              <div class="ml-3" style="width: calc(100% - 60px)">
                <div class="w-full flex justify-start items-center">
                  <div
                    class={[
                      "mr-1",
                      "font-size-10px",
                      "px-[5px]",
                      "py-[5px]",
                      `color${row.status}`,
                      ,
                    ]}
                  >
                    {row.status_text}
                  </div>
                  <div>
                    <vText
                      type="button"
                      value={row.product_no}
                      copy={true}
                      onClick={() => handleOpen(addref, row.id, "view")}
                    ></vText>
                  </div>
                </div>

                <vText value={row.product_category_text}></vText>
                <div class="flex justify-start mb-1">
                  {row.competing_products_link &&
                    row.competing_products_link.slice(0, 2).map((r, i) => (
                      <a class="base-text-color mr-4" onClick={() => navTo(r)}>
                        {" "}
                        {r && (
                          <span>
                            竞品{i + 1}
                            <svg-icon
                              class="inline-block text-purple-600"
                              icon-class="arrow_more_right"
                            />
                          </span>
                        )}
                      </a>
                    ))}
                </div>
                <div class="flex justify-start">
                  {row.purchase_days && row.purchase_days > 0 ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="采购天数"
                      placement="top"
                    >
                      <div class="btn-style">{row.purchase_days} 天</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row.min_order ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="起批量"
                      placement="top"
                    >
                      <div class="btn-style">{row.min_order} 件起批</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                  {row.logistic_attr_text ? (
                    <el-tooltip
                      class="item"
                      effect="dark"
                      placement="top"
                      content="物流属性"
                      raw-content
                    >
                      <div class="btn-style">{row.logistic_attr_text}</div>
                    </el-tooltip>
                  ) : (
                    ""
                  )}
                </div>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "产品名称",
      width: 300,
      field: "product_title",
      line: 2,
    },
    {
      title: "属性",
      width: 200,
      field: "product_title",
      slots: {
        default: ({ row }) => {
          let specification_text = row.specification.length
            ? row.specification.map((i) => {
                if (i) {
                  i.text = i.label + ":" + i.value;
                  return i.text;
                } else {
                  return i;
                }
              })
            : "";
          return (
            <div>
              <div>{row.attribute_type_text}</div>
              {row.attribute_type == 2 && specification_text.length
                ? specification_text.map((i) => {
                    return <vText value={i}></vText>;
                  })
                : ""}
            </div>
          );
        },
      },
    },
    {
      title: "生成SKU",
      width: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="flex">
                {row.sku_list.slice(0, 3).map((i, j) => {
                  return (
                    <span
                      class="cursor-pointer text-[#3487ff]"
                      onClick={() => handleView(i)}
                    >
                      {i.sku} {j < row.sku_list.length - 2 ? ";" : ""}
                    </span>
                  );
                })}
              </div>
              {row.sku_list.length > 3 ? (
                <span
                  class="cursor-pointer text-[#3487ff]"
                  onClick={() => handleViewMore(row)}
                >
                  更多>>
                </span>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
    {
      title: "开发审核备注",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          const review_remark = row.review_remark ? parseHTML(row.review_remark) : "";
          return (
            <div class="flex justify-start">
              <vText value={review_remark} line={2}></vText>
            </div>
          );
        },
      },
    },
    {
      title: "人员信息",
      width: 220,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <span className="column-label">开发人员：</span>
                <span className="column-value">{row.developer_text || " - "}</span>
              </div>
              <div>
                <span className="column-label">开发审核：</span>
                <span className="column-value">{row.reviewer_text || " - "}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "时间信息",
      width: 230,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <span className="column-label">添加：</span>
                <span className="column-value">{row.create_time || " - "}</span>
              </div>
              <div>
                <span className="column-label">开发审核：</span>
                <span className="column-value">{row.review_time || " - "}</span>
              </div>
            </div>
          );
        },
      },
    },
    {
      title: "操作",
      width: 120,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return (
            <div class="flex flex-wrap">
              {![6, 5].includes(row.status) && (
                <div>
                  <VButton
                    auth="/goods/task/develop/edit"
                    type="primary"
                    link
                    onClick={() => handleOpen(addref, row.id, "edit")}
                  >
                    编辑
                  </VButton>
                </div>
              )}
              {row.status == 1 || row.status == 4 ? (
                <div>
                  <VButton
                    auth="/goods/task/develop/delete"
                    type="danger"
                    link
                    loading={loadings.del}
                    onClick={() => handleDel(row.id)}
                  >
                    删除
                  </VButton>
                </div>
              ) : (
                ""
              )}
              {row.status == 2 ? (
                <div>
                  <VButton
                    auth="/goods/task/develop/audit"
                    type="primary"
                    link
                    loading={loadings.submitAuditRow}
                    onClick={() => handleDevelopmentAudit(row)}
                  >
                    开发审核
                  </VButton>{" "}
                </div>
              ) : (
                ""
              )}
              {row.status == 3 || (row.status == 6 && row.is_operation_check) ? (
                <div>
                  <VButton
                    auth="/goods/task/develop/operationaudit"
                    type="primary"
                    link
                    loading={loadings.submitAuditRow}
                    onClick={() => handleOperationAudit(row)}
                  >
                    运营审核
                  </VButton>{" "}
                </div>
              ) : (
                ""
              )}
              {row.product_fee_list.find((i) => i.check_status == 1) &&
              row.status !== 5 ? (
                <div>
                  <VButton
                    auth="/goods/task/develop/createSKU"
                    type="primary"
                    link
                    onclick={() => createSKU(row.id)}
                  >
                    生成SKU
                  </VButton>
                </div>
              ) : (
                ""
              )}
              <div>
                <el-button type="primary" link onClick={() => handleLog(row.id)}>
                  日志
                </el-button>
              </div>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "list",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        return api.query({ ...form, ...page }).then((res) => {
          getCount(res.data.count);

          const totalItem =
            res.data.count.find((i) => i.status == form.status) || res.data.count[0];
          expandStatus.value = false;
          return {
            list: res.data.list,
            total: totalItem?.count,
          };
        });
      },
    },
  },
});
const defaultProps = {
  children: "son",
  label: "name",
  value: "id",
  checkStrictly: false,
  multiple: true,
};

const getCount = (countList) => {
  tabList.value = countList;
  nextTick(() => {
    tabsLoad.value = false; // 先隐藏 teleport 内容
    nextTick(() => {
      tabsLoad.value = true; // 再重新显示
    });
  });
};

// 下拉数据
const fetchOption = () => {
  getOptions({
    name: [
      "product.Product",
      "goods.GoodsSkuSalesInfo",
      "goods.GoodsSku",
      "product.ProductFee",
    ],
  }).then((res) => {
    options.value = res.data;
  });
};

const productLog = ref();
const handleLog = (id) => {
  productLog.value.open(id);
};
// 新增
const add = () => {
  handleOpen(addref, "", "add");
};
// 打开弹窗
/*
 params:
 ref 组件ref
 id:选中项id
 type:view/copy 查看和复制
*/
const handleOpen = (ref, id, type) => {
  nextTick(() => {
    ref.value.open(id, type);
  });
};
// 删除
const handleDel = (id) => {
  ElMessageBox.confirm("此操作将永久删除该产品, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "btnFalses",
  }).then(() => {
    loadings.del = true;
    api
      .del({ productId: id ? [id] : records.value.map((item) => item.id) })
      .then((res) => {
        ElMessage({
          type: "success",
          message: res.message,
        });
        queryForm();
      })
      .finally(() => {
        loadings.del = false;
      });
  });
};
// 审核
const handleAudit = (row) => {
  const records = getSelectRow();
  if (!row) {
    if (records.length == 0) return ElMessage.error("至少勾选一个");
  }
  const item = row ? [row] : records;

  const product_ids = records.map((i) => {
    return i.id;
  });
  const specification =
    item.length == 1 ? (item[0].attribute_type == 2 ? item[0].specification : []) : [];
  nextTick(() => {
    AuditRef.value.open({
      product_ids: row ? item[0].id : product_ids,
      review_opinion: true,
      review_remark: "",
      specification,
    });
  });
};

// 单个开发审核
const handleDevelopmentAudit = (row) => {
  addref.value.open(row.id, "development-audit");
};

// 单个运营审核
const operationAuditRef = ref();
const handleOperationAudit = async (row) => {
  try {
    let { data } = await api.operationReviewList({ product_id: [row.id] });
    operationAuditRef.value?.open(data, row);
  } catch (error) {
    console.error(error);
  }
};

// 批量运营审核
const BatchOperationAuditRef = ref();
const handleBatchOperationAudit = async (row) => {
  let records;
  if (row) {
    records = [row.id];
  } else {
    if (!isHandle()) return;
    records = getSelectRow().map((item) => item.id);
  }

  try {
    let { data, code } = await api.operationReviewList({ product_id: records });
    if (code != 200) return;
    BatchOperationAuditRef.value?.open(data);
  } catch (error) {
    console.error(error);
  }
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
//撤回
const handleWithdraw = () => {
  if (!isHandle()) return;
  const records = getSelectRow();
  if (records?.length > 1) return ElMessage.warning("只能选择一条数据!");
  const { status, id } = records[0];
  if (status == 3 || status == 2) {
    ElMessageBox({
      title: "撤回确认",
      message: "是否确认撤回到上一个状态?",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
    }).then(async (action) => {
      try {
        const { code, message } = await api.withdraw({ product_id: id });
        if (code != 200) return ElMessage.error(message);
        ElMessage.success(message);
        refresh();
      } catch (e) {
        throw Error(e);
      }
    });
  } else {
    return ElMessage.warning("只允许撤回状态=待运营审核/待开发审核的数据!");
  }
};
// 复制商品
const copy = () => {
  if (!isHandle()) return;
  const records = getSelectRow();
  if (records.length > 1) return ElMessage.error("只能复制一个产品!");
  handleOpen(addref, records[0].id, "copy");
};
// 提交审核
const SubmitAuditRef = ref();
const submitAudit = (type, productId) => {
  const records = getSelectRow().map((i) => {
    return i.id;
  });
  if (!productId) {
    if (records.length == 0) return ElMessage.error("至少勾选一个");
  }

  const spu_id = productId ? [productId] : records;
  SubmitAuditRef.value.open(type, spu_id);
};

const submitOperationAudit = () => {
  const product_ids = getSelectRow().map((i) => {
    return i.id;
  });
  if (records.length == 0) return ElMessage.error("至少勾选一个");
  ElMessageBox.confirm("此操作将跳过开发审核，是否继续提交至运营审核？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    api
      .submitOperation({
        product_ids,
      })
      .then((res) => {
        ElMessage.success("操作成功");
        queryForm();
      });
  });
};

const DerivedCenterRef = ref();
const handleExport = (val) => {
  const records = getSelectRow().map((i) => {
    return i.product_no;
  });

  const uniqueArray = [...new Set(records)];

  let condition = {};
  if (uniqueArray.length) {
    condition.product_no = uniqueArray;
  } else {
    condition = tableRef.value.getQueryForm();
  }
  DerivedCenterRef.value.open({
    tag_name: val,
    condition,
  });
};

const setForm = (val) => {
  nextTick(() => {
    tableRef.value.setForm(val);
  });
};
// 选择品牌类型
const changeCategory = (val) => {
  if (val && val.length) {
    const lastLevelIDs = val.map((categoryPath) => categoryPath[categoryPath.length - 1]);
    const form = tableRef.value.getForm();
    setForm({ ...form, product_category: lastLevelIDs });
  } else {
    const form = tableRef.value.getForm();
    setForm({ ...form, product_category: 0 });
  }
};
// 切换状态
const handleClick = (tab, even) => {
  // activeName.value = tab.props.name;
  const form = tableRef.value.getForm();
  tableRef.value.setForm({ ...form, status: tab.props.name });
  queryForm(tabList.value);
};
const isHandle = () => {
  const records = getSelectRow();
  return !records.length ? ElMessage.error("请先选择行!") && false : true;
};

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords();
};
//生成sku
const createSKU = (productId) => {
  router.push({
    path: "/task/product/add",
    query: {
      productId,
      type: "createSKU",
    },
  });
};

const queryForm = (count) => {
  nextTick(() => {
    const form = tableRef.value.getForm();
    tableRef.value.setForm({
      ...form,
      count,
    });
    tableRef.value.query();
  });
};

const navTo = (url) => {
  if (!url) return;
  window.open(url, "_blank");
};

const parseHTML = (html) => {
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, "text/html");
  const root = doc.documentElement;
  return Array.from(root.childNodes).map((node) => {
    return node.textContent;
  });
};

const handleKeyUp = (event) => {
  if (event.keyCode === 13 || event.key === "Enter") {
    queryForm();
    event.stopPropagation();
  }
};

// 导入
const importExcelRef = ref();
const handleImport = () => {
  nextTick(() => {
    const params = {
      title: "批量导入开发任务模版（V0.4）.xlsx",
      tempApi:
        "https://xc-goods.oss-cn-shenzhen.aliyuncs.com/goods/20250429/%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E5%BC%80%E5%8F%91%E4%BB%BB%E5%8A%A1%E6%A8%A1%E7%89%88%EF%BC%88V0.4%EF%BC%89174591125522036.4%EF%BC%89.xlsx",
      importApi: api.productImport,
    };
    importExcelRef.value?.acceptParams(params);
  });
};

const computedCount = (row) => {
  if (row.product_fee_list.length) {
    const count = row.product_fee_list.reduce((acc, cur) => {
      if (cur.check_status != 2) {
        return acc + cur.suggest_prepare_count;
      }
      return acc;
    }, 0);
    return count || "--";
  }
  return "--";
};

// 全部展开 / 收起
const handleExpand = () => {
  expandStatus.value = !expandStatus.value;
  if (expandStatus.value) {
    tableRef.value.$table.setAllRowExpand(true);
  } else {
    tableRef.value.$table.setAllRowExpand(false);
  }
};

// 查看
const handleView = (row) => {
  router.push({
    path: "/task/product/detail",
    query: {
      spuId: row.spu_id,
      sku: row.sku,
    },
  });
};
// 更多
const GenerateSKURef = ref();
const handleViewMore = (row) => {
  GenerateSKURef.value.open(row.sku_list);
};

const getTextColor = (val) => {
  if (val == 0) {
    return "#3366f1";
  } else if (val == 1) {
    return "#00ac76";
  } else if (val == 2) {
    return "#ff0000";
  } else if (val == 3) {
    return "#faad14";
  }
};
</script>
<style lang="scss" scoped>
.selectClass {
  &:deep(.el-select__wrapper) {
    background-color: var(--base-small-bg-color) !important;
  }
}

.form-item-bgColor {
  background-color: var(--base-small-bg-color) !important;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.vxe-toolbar) {
  padding-top: 8px;
}

:deep(.is--expand-row) {
  background-color: var(--base-small-bg-color);
}
:deep(.is--expand-row .cell--fixed) {
  background-color: var(--base-small-bg-color);
}
</style>
<style lang="scss">
.rate-style.text-left {
  text-align: left !important;
}

.rate-style {
  font-size: 16px;
  font-weight: 600;
  color: #9da1ad;
  line-height: 22px;
  background: linear-gradient(180deg, #ff9897 0%, #f650a0 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-align: left;
}

.column-label {
  color: var(--base-sub-text-color);
}

.column-value {
  color: var(--base-text-color);
}

.column-label-gray {
  color: var(--base-text-color);
}

// 草稿
.color1 {
  color: #00ac76;
  background: rgba(0, 172, 118, 0.2);
}

//待审核
.color2 {
  color: #faad14;
  background: rgba(250, 173, 20, 0.2);
}

//审核通过
.color3 {
  color: #3366f1;
  background: rgba(51, 102, 241, 0.1);
}

//审核未通过
.color4 {
  color: #ff0000;
  background: rgba(229, 1, 19, 0.2);
}

//已完成
.color5,
.color6 {
  color: #00ac76;
  background: rgba(0, 172, 118, 0.2);
}

.table-inside {
  // background-color: var(--base-small-bg-color) !important;
  td {
    padding: 4px;
    position: relative;
  }
  tr + tr {
    border-top: 1px solid var(--base-border-color);
  }
  td + td::before {
    content: "";
    display: inline-block;
    position: absolute;
    left: 0;
    top: 25%;
    bottom: 25%;
    width: 1px;
    // height: calc(100% - 20px);
    background-color: var(--base-border-color);
  }
  span {
    color: var(--base-sub-text-color);
  }
}
</style>
